var gulp = require('gulp');
var sass = require('gulp-sass');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var twig = require('gulp-twig');
var htmlbeautify = require('gulp-html-beautify');
var sourcemap = require('gulp-sourcemaps');
var del = require('del');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync').create();

gulp.task('sass', function () {
    return gulp.src('app/scss/**/*.scss')
        .pipe(sourcemap.init())
        .pipe(sass())
        .pipe(sourcemap.write('maps'))
        .pipe(gulp.dest('app/css'))
        .pipe(browserSync.reload({
            stream: true
        }))
});

gulp.task('twig', function () {
    return gulp.src('app/twig/*.twig')
        .pipe(twig())
        .pipe(gulp.dest('app'))
        .pipe(browserSync.reload({
            stream: true
        }))
});

gulp.task('useref', function () {
    return gulp.src('app/*.html')
        .pipe(useref())
        // Minifies only if it's a JavaScript file
        .pipe(gulpIf('*.js', uglify()))
        // Minifies only if it's a CSS file
        .pipe(gulpIf('*.css', cssnano()))
        .pipe(htmlbeautify())
        .pipe(gulp.dest('dist'))
});

gulp.task('images', function () {
    return gulp.src('app/images/**/*.+(png|jpg|gif|svg)')
        // Caching images that ran through imagemin
        .pipe(cache(imagemin({
            interlaced: true,
            progressive: true,
            optimizationLevel: 5,
            svgoPlugins: [{removeViewBox: true}]
        })))
        .pipe(gulp.dest('dist/images'))
});

gulp.task('browserSync', function () {
    browserSync.init({
        server: {
            baseDir: 'app',
            directory: true
        },
    });
});

gulp.task('fonts', function () {
    return gulp.src('app/fonts/**/*')
        .pipe(gulp.dest('dist/fonts'))
});

gulp.task('clean:dist', function () {
    return del.sync('dist');
});

gulp.task('cache:clear', function (callback) {
    return cache.clearAll(callback)
})

gulp.task('watch', ['browserSync', 'sass'], function () {
    gulp.watch('app/scss/**/*.scss', ['sass']);
    gulp.watch('app/twig/**/*.twig', ['twig']);
    // Reloads the browser whenever HTML or JS files change
    gulp.watch('app/html/*.html', browserSync.reload);
    gulp.watch('app/js/**/*.js', browserSync.reload);
});

// gulp.task('build', [`clean:dist`, `sass`, `useref`, `images`, `fonts`], function () {
//     console.log('Building files');
// })

gulp.task('build', function (callback) {
    runSequence('clean:dist',
        ['sass', 'twig', 'useref', 'images', 'fonts'],
        callback
    )
})

gulp.task('default', function (callback) {
    runSequence(['sass', 'twig', 'browserSync', 'watch'],
        callback
    )
})